from django.shortcuts import render, redirect, get_object_or_404
from django.contrib.auth.decorators import login_required
from django.contrib import messages
from django.http import JsonResponse
from .models import Notification, Follow, Report, Like, Favorite, Comment, CommentLike
from story.models import Story
from user.models import UserProfile, UserActivity
import json
from django.views.decorators.http import require_POST, require_GET


# Create your views here.

@login_required
def notification_list(request):
    notifications = Notification.objects.filter(recipient=request.user)
    return render(request, 'interactive/notification_list.html', {
        'notifications': notifications
    })


@login_required
def notification_read(request, pk):
    notification = get_object_or_404(Notification, pk=pk, recipient=request.user)
    notification.is_read = True
    notification.save()
    return redirect('interactive:notification_list')


@login_required
def notification_read_all(request):
    Notification.objects.filter(recipient=request.user, is_read=False).update(is_read=True)
    return redirect('interactive:notification_list')


@login_required
def follow_user(request, user_id):
    user_to_follow = get_object_or_404(User, pk=user_id)
    if request.user != user_to_follow:
        Follow.objects.get_or_create(follower=request.user, following=user_to_follow)
        messages.success(request, f'已关注 {user_to_follow.username}')
    return redirect('user:profile', username=user_to_follow.username)


@login_required
def unfollow_user(request, user_id):
    user_to_unfollow = get_object_or_404(User, pk=user_id)
    Follow.objects.filter(follower=request.user, following=user_to_unfollow).delete()
    messages.success(request, f'已取消关注 {user_to_unfollow.username}')
    return redirect('user:profile', username=user_to_unfollow.username)


@login_required
def report_story(request, story_id):
    story = get_object_or_404(Story, pk=story_id)
    if request.method == 'POST':
        report_type = request.POST.get('report_type', 'other')
        description = request.POST.get('description', '').strip()
        if description:
            Report.objects.create(
                reporter=request.user,
                story=story,
                report_type=report_type,
                description=description
            )
            messages.success(request, '举报已提交，我们会尽快处理')
        else:
            messages.error(request, '请填写举报原因')
    return redirect('story:detail', pk=story_id)


@login_required
def like_story(request, story_id):
    story = get_object_or_404(Story, pk=story_id)
    like, created = Like.objects.get_or_create(user=request.user, story=story)

    if created:
        # 创建通知
        if request.user != story.author:
            Notification.objects.create(
                recipient=story.author,
                sender=request.user,
                notification_type='like',
                content=f'{request.user.username} 点赞了你的故事《{story.title}》',
                related_story=story
            )

        # 记录用户活动
        UserActivity.objects.create(
            user=request.user,
            activity_type='like_story',
            activity_data={'story_id': story.id, 'title': story.title}
        )

        messages.success(request, '点赞成功！')
    else:
        like.delete()
        messages.success(request, '已取消点赞')

    return redirect('story:detail', pk=story_id)


@login_required
def favorite_story(request, story_id):
    story = get_object_or_404(Story, pk=story_id)
    favorite, created = Favorite.objects.get_or_create(user=request.user, story=story)

    if created:
        # 记录用户活动
        UserActivity.objects.create(
            user=request.user,
            activity_type='favorite_story',
            activity_data={'story_id': story.id, 'title': story.title}
        )

        messages.success(request, '收藏成功！')
    else:
        favorite.delete()
        messages.success(request, '已取消收藏')

    return redirect('story:detail', pk=story_id)


@login_required
def comment_story(request, story_id):
    story = get_object_or_404(Story, pk=story_id)

    if request.method == 'POST':
        content = request.POST.get('content', '').strip()
        if content:
            # 创建评论
            comment = Comment.objects.create(
                user=request.user,
                story=story,
                content=content
            )

            # 创建通知
            if request.user != story.author:
                Notification.objects.create(
                    recipient=story.author,
                    sender=request.user,
                    notification_type='comment',
                    content=f'{request.user.username} 评论了你的故事《{story.title}》',
                    related_story=story
                )

            # 记录用户活动
            UserActivity.objects.create(
                user=request.user,
                activity_type='comment_story',
                activity_data={'story_id': story.id, 'title': story.title}
            )

            messages.success(request, '评论发表成功！')
        else:
            messages.error(request, '评论内容不能为空！')

    return redirect('story:detail', pk=story_id)


@login_required
def reply_comment(request, comment_id):
    comment = get_object_or_404(Comment, pk=comment_id)
    story = comment.story
    
    if request.method == 'POST':
        content = request.POST.get('content', '').strip()
        if content:
            # 创建回复评论
            reply = Comment.objects.create(
                user=request.user,
                story=story,
                content=content,
                parent_comment=comment
            )
            
            # 创建通知给被回复的评论作者
            if request.user != comment.user:
                Notification.objects.create(
                    recipient=comment.user,
                    sender=request.user,
                    notification_type='comment',
                    content=f'{request.user.username} 回复了你在《{story.title}》下的评论',
                    related_story=story
                )
            
            # 同时通知故事作者（如果故事作者不是评论作者也不是回复者）
            if story.author != comment.user and story.author != request.user:
                Notification.objects.create(
                    recipient=story.author,
                    sender=request.user,
                    notification_type='comment',
                    content=f'{request.user.username} 在你的故事《{story.title}》下回复了 {comment.user.username}',
                    related_story=story
                )
            
            # 记录用户活动
            UserActivity.objects.create(
                user=request.user,
                activity_type='reply_comment',
                activity_data={
                    'story_id': story.id, 
                    'title': story.title,
                    'parent_comment_id': comment.id,
                    'parent_comment_user': comment.user.username
                }
            )
            
            messages.success(request, '回复发表成功！')
        else:
            messages.error(request, '回复内容不能为空！')
    
    return redirect('story:detail', pk=story.id)


@require_GET
def get_comments(request, story_id):
    """获取故事的评论列表，只返回已审核的评论"""
    story = get_object_or_404(Story, id=story_id)
    
    # 只获取已批准的评论
    comments = Comment.objects.filter(
        story=story,
        parent_comment=None,
        status='approved'  # 只返回已批准的评论
    ).select_related('user').order_by('-created_at')
    
    comments_data = []
    for comment in comments:
        # 只获取已批准的回复
        replies = Comment.objects.filter(
            parent_comment=comment,
            status='approved'  # 只返回已批准的回复
        ).select_related('user').order_by('created_at')
        
        replies_data = []
        for reply in replies:
            # 获取用户头像URL
            avatar_url = None
            if hasattr(reply.user, 'profile'):
                profile = reply.user.profile
                if profile.avatar and hasattr(profile.avatar, 'url'):
                    avatar_url = profile.avatar.url
            
            if not avatar_url:
                avatar_url = '/static/admin/img/tx.png'
            
            replies_data.append({
                'id': reply.id,
                'content': reply.content,
                'created_at': reply.created_at.strftime('%Y-%m-%d %H:%M'),
                'user': {
                    'id': reply.user.id,
                    'username': reply.user.username,
                    'avatar': avatar_url
                }
            })
        
        # 获取评论用户头像URL
        avatar_url = None
        if hasattr(comment.user, 'profile'):
            profile = comment.user.profile
            if profile.avatar and hasattr(profile.avatar, 'url'):
                avatar_url = profile.avatar.url
        
        if not avatar_url:
            avatar_url = '/static/admin/img/tx.png'
        
        comments_data.append({
            'id': comment.id,
            'content': comment.content,
            'created_at': comment.created_at.strftime('%Y-%m-%d %H:%M'),
            'user': {
                'id': comment.user.id,
                'username': comment.user.username,
                'avatar': avatar_url
            },
            'replies': replies_data,
            'likes_count': comment.likes.count()
        })
    
    return JsonResponse({'comments': comments_data})

@login_required
@require_POST
def add_comment(request, story_id):
    """添加评论或回复，初始状态为待审核"""
    if not request.user.is_authenticated:
        return JsonResponse({'status': 'error', 'message': '请先登录'}, status=401)
    
    try:
        data = json.loads(request.body)
        content = data.get('content', '').strip()
        parent_id = data.get('parent_id')
        
        if not content:
            return JsonResponse({'status': 'error', 'message': '评论内容不能为空'}, status=400)
        
        story = get_object_or_404(Story, id=story_id)
        
        # 创建评论
        if parent_id:
            # 如果是回复
            parent_comment = get_object_or_404(Comment, id=parent_id)
            
            comment = Comment.objects.create(
                user=request.user,
                story=story,
                content=content,
                parent_comment=parent_comment,
                status='pending'  # 设置为待审核状态
            )
            
            # 如果评论者不是父评论作者，给父评论作者发送通知
            if request.user != parent_comment.user:
                Notification.objects.create(
                    recipient=parent_comment.user,
                    sender=request.user,
                    notification_type='comment',
                    content=f'{request.user.username} 回复了你在《{story.title}》下的评论',
                    related_story=story
                )
        else:
            # 创建新评论
            comment = Comment.objects.create(
                user=request.user,
                story=story,
                content=content,
                status='pending'  # 设置为待审核状态
            )
            
            # 如果评论者不是故事作者，给故事作者发送通知
            if request.user != story.author:
                Notification.objects.create(
                    recipient=story.author,
                    sender=request.user,
                    notification_type='comment',
                    content=f'{request.user.username} 评论了你的故事《{story.title}》',
                    related_story=story
                )
        
        return JsonResponse({
            'status': 'success',
            'message': '评论已提交，等待审核'
        })
    
    except json.JSONDecodeError:
        return JsonResponse({'status': 'error', 'message': '无效的请求格式'}, status=400)
    except Exception as e:
        return JsonResponse({'status': 'error', 'message': str(e)}, status=500)

@login_required
@require_POST
def like_comment(request, comment_id):
    """点赞或取消点赞评论"""
    if not request.user.is_authenticated:
        return JsonResponse({'status': 'error', 'message': '请先登录'}, status=401)
    
    try:
        comment = get_object_or_404(Comment, id=comment_id)
        like, created = CommentLike.objects.get_or_create(user=request.user, comment=comment)
        
        if not created:
            # 如果已经点赞，则取消点赞
            like.delete()
            is_liked = False
        else:
            # 新增点赞
            is_liked = True
            
            # 如果点赞者不是评论作者，给评论作者发送通知
            if request.user != comment.user:
                Notification.objects.create(
                    recipient=comment.user,
                    sender=request.user,
                    notification_type='like',
                    content=f'{request.user.username} 点赞了你的评论',
                    related_story=comment.story
                )
        
        # 获取最新点赞数量
        likes_count = CommentLike.objects.filter(comment=comment).count()
        
        return JsonResponse({
            'status': 'success',
            'liked': is_liked,
            'likes_count': likes_count
        })
    except Exception as e:
        return JsonResponse({'status': 'error', 'message': str(e)}, status=500)
